package com.shire.shire_interface.service.validation;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.constants.WxConstants;
import com.shire.shire_interface.dao.validation.WxValidationRecordDao;
import com.shire.shire_interface.model.command.WxCommand;
import com.shire.shire_interface.model.friend.WxFriendLog;
import com.shire.shire_interface.model.user.WxAccount;
import com.shire.shire_interface.model.validation.WxValidationRecord;
import com.shire.shire_interface.model.validation.WxValidationRecordExample;
import com.shire.shire_interface.service.account.WxAccountService;
import com.shire.shire_interface.service.friend.WxFriendLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者:  sll
 * 时间:  2019/8/14 15:35
 */
@Service
public class WxValidationRecordService {
    @Resource
    private WxValidationRecordDao wxValidationRecordDao;
    @Resource
    private WxFriendLogService friendLogService;
    @Resource
    private WxAccountService accountService;

    public List<WxValidationRecord> selectByExample(WxValidationRecordExample example) {
        return wxValidationRecordDao.selectByExampleWithBLOBs(example);
    }

    public WxValidationRecord getRecordByWxId(String wxAccount, String wxId){
        WxValidationRecordExample example = new WxValidationRecordExample();
        example.createCriteria().andWxaccountEqualTo(wxAccount).andWxidEqualTo(wxId);

        List<WxValidationRecord> recordList = wxValidationRecordDao.selectByExample(example);
        if (recordList.size() > 0){
            return recordList.get(0);
        }
        return null;
    }

    public void updateRecordByCmd(WxCommand command){
        WxValidationRecord record = wxValidationRecordDao.selectByPrimaryKey(command.getTaskid());
        record.setCmdstatus(command.getRststatus());
        record.setUpdateTime(new Date());
        wxValidationRecordDao.updateByPrimaryKeySelective(record);
    }

    public List<WxValidationRecord> getValidationRecord(Integer csId, List<String> wxAccounts, WxConstants.ValidationStatus status){
        WxValidationRecordExample recordExample = new WxValidationRecordExample();
        WxValidationRecordExample.Criteria criteria = recordExample.createCriteria();
        WxValidationRecordExample.Criteria or = recordExample.or();
        criteria.andCsidEqualTo(csId)
                .andStatusEqualTo(status.getCode()).andCmdidIsNull();
        or.andCsidEqualTo(csId)
                .andStatusEqualTo(status.getCode()).andCmdstatusEqualTo(-1);

        if (wxAccounts.size() > 0) {
            criteria.andWxaccountIn(wxAccounts);
            or.andWxaccountIn(wxAccounts);
        }

        return wxValidationRecordDao.selectByExampleWithBLOBs(recordExample);
    }

    public int insertBySelective(WxValidationRecord wxValidationRecord) {
        return wxValidationRecordDao.insertSelective(wxValidationRecord);
    }

    public int updateRecord(WxValidationRecord record){
        return wxValidationRecordDao.updateByPrimaryKeySelective(record);
    }

    public int deleteByIds(List<Integer> idList){
        WxValidationRecordExample example = new WxValidationRecordExample();
        example.createCriteria().andIdIn(idList);
        return  wxValidationRecordDao.deleteByExample(example);
    }

    public void syncValidationForAccount(WxAccount account, JSONArray validationRecords){
        WxValidationRecordExample recordExample = new WxValidationRecordExample();
        recordExample.createCriteria().andWxaccountEqualTo(account.getWxid());
        List<WxValidationRecord> validationRecordList = selectByExample(recordExample);
        List<Integer> idList = new ArrayList<>();
        for (WxValidationRecord record : validationRecordList) {
            idList.add(record.getId());
        }


        for (Object validationRecord : validationRecords) {
            JSONObject jsonRec = JSONObject.parseObject(JSONUtils.toJSONString(validationRecord));
            Integer sex = jsonRec.getInteger("sex");
            String province = jsonRec.getString("province");
            String nick = jsonRec.getString("nick");
            String area = jsonRec.getString("area");
            Integer friendScene = jsonRec.getInteger("friendScene");
            String avatar = jsonRec.getString("avatar");
            String signature = jsonRec.getString("signature");
            String alias = jsonRec.getString("alias");
            String city = jsonRec.getString("city");
            String wxId = jsonRec.getString("wxId");
            String strangerId = jsonRec.getString("strangerId");
            Integer helloType = jsonRec.getInteger("helloType");
            String msgs = jsonRec.getJSONArray("msgs").toJSONString();

            WxValidationRecord record ;
            record = getRecordByWxId(account.getWxid(),wxId);
            if (record == null){
                record = new WxValidationRecord();
            }

            //状态没有发生变化，不更新
            if (record.getId()!= null && record.getStatus() == helloType){
                idList.remove(record.getId());
                continue;
            }

            record.setCsid(account.getCsid());
            record.setStatus(helloType);
            record.setWxaccount(account.getWxid());
            record.setWxid(wxId);
            record.setAvatar(avatar);
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            record.setNick(nick);
            record.setSex(sex);
            record.setArea(area);
            record.setProvince(province);
            record.setFriendscene(friendScene);
            record.setSignature(signature);
            record.setAlias(alias);
            record.setStrangerid(strangerId);
            record.setMsglist(msgs);

            if (idList.contains(record.getId()))
                idList.remove(record.getId());

            if (record.getId() == null){
                insertBySelective(record);
            }else {
                if (record.getStatus() == WxConstants.ValidationStatus.WAIT.getCode()){
                    record.setCmdstatus(-100);
                    record.setCmdstatus(-1);
                }
                updateRecord(record);
            }

            if (record.getStatus() == 2) {
                WxFriendLog friendLog = friendLogService.getFriendLogByWxId(account.getCsid(), account.getWxid(), wxId);
                if (friendLog == null) {
                    friendLog = new WxFriendLog();
                }
                friendLog.setCsid(account.getCsid());
                friendLog.setCreatetime(new Date());
                friendLog.setFriendwxid(wxId);
                friendLog.setFriendnick(nick);
                friendLog.setAddtype(2);
                friendLog.setWxaccount(account.getWxid());
                friendLog.setAddresult(0);
                if (friendLog.getId() == null){
                    friendLogService.inserFriendLog(friendLog);
                }else {
                    friendLogService.updateFriendLog(account,friendLog);
                }
            }

        }

        if (idList.size() > 0)
            deleteByIds(idList);
    }
}
